//+------------------------------------------------------------------+
//|                                              KLineReminderEA.mq5 |
//|                        Copyright 2023, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"

bool triggered = false; // 防止重复触发标志

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   // 设置1秒定时器
   EventSetTimer(1);
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
   EventKillTimer(); // 删除定时器
}

//+------------------------------------------------------------------+
//| Timer function                                                   |
//+------------------------------------------------------------------+
void OnTimer()
{
   datetime currentTime = TimeCurrent();                // 获取当前服务器时间
   datetime nextBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);   // 计算下一根K线开始时间
   int remainingSeconds = (int)(nextBarTime - currentTime); // 计算剩余秒数
   Print(remainingSeconds,"====计算剩余秒数=",nextBarTime);
   // 当剩余5秒且未触发过时执行
   if(remainingSeconds == -5 && !triggered)
   {
      Print(remainingSeconds,"====计算剩余秒数=",nextBarTime);
      triggered = true; // 设置触发标志
      Alert("5 seconds before new bar! Current Time: ", TimeToString(currentTime));
      // 此处可添加交易操作，例如：
      // OrderSend(...);
   }

   // 当剩余时间超过5秒时重置触发标志
   if(remainingSeconds > -5)
   {
      triggered = false;
   }
}